<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="chinese">
<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">



  
  
    
      
    
    
      
    
  <script src="//cdn.jsdelivr.net/npm/pace-js@1/pace.min.js"></script>
  <link href="//cdn.jsdelivr.net/npm/pace-js@1/themes/blue/pace-theme-minimal.min.css" rel="stylesheet">







<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Hexo, NexT">










<meta name="description" content="第十三章 通过异常处理错误Java基本理念是 “结构不佳的代码不能运行。” 发现错误的理想时机是在程序的编译过程中。异常处理是Java唯一正式的报告机制。 13.1 概念&amp;emsp;&amp;emsp;使用异常处理能够降低处理代码的复杂度。使用异常的另一个好处是，它能够明显的降低代码的复杂程度，避免了大量的错误检查，只需要在一个特定的地方进行异常捕获，并且不需要做任何判断，异常捕获区能够捕获所有发生的错误">
<meta name="keywords" content="Java Php hexo Thinking in Java">
<meta property="og:type" content="article">
<meta property="og:title" content="Thinking in Java 第十二章">
<meta property="og:url" content="http://yoursite.com/2019/08/07/Thinking-in-Java-第十二章/index.html">
<meta property="og:site_name" content="坚持就是胜利">
<meta property="og:description" content="第十三章 通过异常处理错误Java基本理念是 “结构不佳的代码不能运行。” 发现错误的理想时机是在程序的编译过程中。异常处理是Java唯一正式的报告机制。 13.1 概念&amp;emsp;&amp;emsp;使用异常处理能够降低处理代码的复杂度。使用异常的另一个好处是，它能够明显的降低代码的复杂程度，避免了大量的错误检查，只需要在一个特定的地方进行异常捕获，并且不需要做任何判断，异常捕获区能够捕获所有发生的错误">
<meta property="og:locale" content="chinese">
<meta property="og:updated_time" content="2020-06-04T02:30:22.245Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Thinking in Java 第十二章">
<meta name="twitter:description" content="第十三章 通过异常处理错误Java基本理念是 “结构不佳的代码不能运行。” 发现错误的理想时机是在程序的编译过程中。异常处理是Java唯一正式的报告机制。 13.1 概念&amp;emsp;&amp;emsp;使用异常处理能够降低处理代码的复杂度。使用异常的另一个好处是，它能够明显的降低代码的复杂程度，避免了大量的错误检查，只需要在一个特定的地方进行异常捕获，并且不需要做任何判断，异常捕获区能够捕获所有发生的错误">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":14,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '190coder'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://yoursite.com/2019/08/07/Thinking-in-Java-第十二章/">





  <title>Thinking in Java 第十二章 | 坚持就是胜利</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="chinese">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">坚持就是胜利</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            Home
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            Categories
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            Archives
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/2019/08/07/Thinking-in-Java-第十二章/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="190coder">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="坚持就是胜利">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">Thinking in Java 第十二章</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">Posted on</span>
              
              <time title="Post created" itemprop="dateCreated datePublished" datetime="2019-08-07T23:40:03+08:00">
                2019-08-07
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">In</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Java/" itemprop="url" rel="index">
                    <span itemprop="name">Java</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h1 id="第十三章-通过异常处理错误"><a href="#第十三章-通过异常处理错误" class="headerlink" title="第十三章 通过异常处理错误"></a>第十三章 通过异常处理错误</h1><p>Java基本理念是 “结构不佳的代码不能运行。”</p>
<p>发现错误的理想时机是在程序的编译过程中。异常处理是Java唯一正式的报告机制。</p>
<h2 id="13-1-概念"><a href="#13-1-概念" class="headerlink" title="13.1 概念"></a>13.1 概念</h2><p>&emsp;&emsp;使用异常处理能够降低处理代码的复杂度。使用异常的另一个好处是，它能够明显的降低代码的复杂程度，避免了大量的错误检查，只需要在一个特定的地方进行异常捕获，并且不需要做任何判断，异常捕获区能够捕获所有发生的错误。这种异常的处理方式与之前的错误处理方式相比，完全的将“正常做的事儿”与“出现问题怎么办”隔离开来。是代码的读写变得更加井井有条。</p>
<h2 id="13-2-基本异常"><a href="#13-2-基本异常" class="headerlink" title="13.2 基本异常"></a>13.2 基本异常</h2><p>对于一个对象引用t，传递给你的时候可能没有被初始化，所以在使用这个对象引用调用执行方法之前，进行合理的判断是非常有必要的。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">if(t==null)&#123;</span><br><span class="line">    throw new NullPointerException();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p> 上面代码中，我们判断当前对象引用是否没有进行初始化，如果没有进行初始化，那么就创建一个NullPointerException（）对象，然后使用throw关键字，将该对象的引用抛出。</p>
<h2 id="13-3-捕获异常"><a href="#13-3-捕获异常" class="headerlink" title="13.3 捕获异常"></a>13.3 捕获异常</h2><p>关键字try后包围的一部分代码块，称作try块，这样做比起之前说的要在每个会产生错误的地方进行判断要容易的多，并且代码的可读性大大增强，产生异常之后抛出的异常必须在某处得到处理，这个地点就是异常处理区，异常处理区紧跟着try块，使用catch关键字表示：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">try&#123; //---&#125;catch(Type1 arg1)&#123; //---&#125;catch(Type2 arg2)&#123;&#125;</span><br></pre></td></tr></table></figure>

<h2 id="13-4-创建自定义异常"><a href="#13-4-创建自定义异常" class="headerlink" title="13.4 创建自定义异常"></a>13.4 创建自定义异常</h2><p>Java中虽然提供了很多默认的异常类型，但是要想完全覆盖会发生的异常情况显然是不现实的，因此我们可以自定义异常来表示我们预期可能会出现的异常。自定义的形式也非常简单，只需要继承一个相似的异常类即可。建立一个新的异常类最贱的方法就是让编译器为你产生默认构造器。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">class SimpleException extends Exception&#123;&#125;  </span><br><span class="line">public class InheritingException &#123;  </span><br><span class="line">    public void f() throws SimpleException&#123;  </span><br><span class="line">        System.out.println(&quot;Throw SimpleException from f&quot;);  </span><br><span class="line">        throw new SimpleException();  </span><br><span class="line">    &#125;  </span><br><span class="line">    public static void main(String[] args) &#123;  </span><br><span class="line">        InheritingException ite = new InheritingException();  </span><br><span class="line">        try&#123;  </span><br><span class="line">            ite.f();  </span><br><span class="line">        &#125;catch(SimpleException e)&#123;  </span><br><span class="line">            System.out.println(&quot;Caught it!&quot;);  </span><br><span class="line">        &#125;  </span><br><span class="line">    &#125; </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>带有参数的构造器</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line">class MyException extends Exception&#123;</span><br><span class="line">    public MyException()&#123;</span><br><span class="line">		</span><br><span class="line">	&#125;</span><br><span class="line">	public MyException(String msg)&#123;</span><br><span class="line">		super(msg);</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br><span class="line">public class FullConstructors &#123;</span><br><span class="line">	public static void f() throws MyException &#123;</span><br><span class="line">		System.out.println(&quot;Throwing myException from f()&quot;);</span><br><span class="line">		throw new MyException();</span><br><span class="line">	&#125;</span><br><span class="line">	public static void g() throws MyException&#123;</span><br><span class="line">		System.out.println(&quot;Throwing myException from g()&quot;);</span><br><span class="line">		throw new MyException(&quot;Originated in g()&quot;);</span><br><span class="line">	&#125;</span><br><span class="line">	public static void main(String[] args) &#123;</span><br><span class="line">		try&#123;</span><br><span class="line">			f();</span><br><span class="line">		&#125;catch(MyException e)&#123;</span><br><span class="line">			e.printStackTrace();</span><br><span class="line">		&#125;</span><br><span class="line">		try&#123;</span><br><span class="line">			g();</span><br><span class="line">		&#125;catch(MyException e)&#123;</span><br><span class="line">			e.printStackTrace(System.out);</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><strong>有参和无参数区别可以从控制台错误信息的眼神看出。标准错误流更加的引人注目。</strong></p>
<h2 id="12-5-异常说明"><a href="#12-5-异常说明" class="headerlink" title="12.5 异常说明"></a>12.5 异常说明</h2><p>Java提供了相应的语法（并强制使用这个语法），使你可以使用礼貌的方式告知客户端程序员某个方法可能会抛出的异常类型，然后客户端程序员就可以进行相应的处理。这就是异常说明，它属于方法声明的一部分，紧跟在形式参数列表之后，使用throws关键字，后面接一个所有潜在异常类型的列表，所以方法定义可能看起来像是这样：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">void f() throws TooBig,TooSmall,DivZero&#123;&#125;;</span><br></pre></td></tr></table></figure>

<h2 id="12-6-捕获所有异常"><a href="#12-6-捕获所有异常" class="headerlink" title="12.6 捕获所有异常"></a>12.6 捕获所有异常</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">catch（Exception e）&#123;</span><br><span class="line">    //---</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ul>
<li>String getMessage（） 获取详细信息</li>
<li>String getLocalizedMessage（）获取用本地语言表示的详细信息</li>
<li>String toString（）返回对Throwable的简单描述</li>
<li>void printStackTrace（）打印Throwable的调用栈轨迹 输出到标准错误流</li>
<li>void printStackTrace（PrintStream）打印Throwable的调用栈轨迹 输出到可选择的流<br>void printStackTrace（PrintStream）打印Throwable的调用栈轨迹 输出到可选择的流</li>
</ul>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line">public class ExceptionMethods &#123;</span><br><span class="line">	public static void main(String[] args) &#123;</span><br><span class="line">		try&#123;</span><br><span class="line">			throw new Exception(&quot;My Exception&quot;);</span><br><span class="line">		&#125;catch(Exception e)&#123;</span><br><span class="line">			System.out.println(&quot;Caught Exception&quot;);</span><br><span class="line">			System.out.println(&quot;getMessage():&quot; + e.getMessage());</span><br><span class="line">			System.out.println(&quot;getLocalizedMessage():&quot; + e.getLocalizedMessage());</span><br><span class="line">			System.out.println(&quot;toString()&quot; + e.toString());</span><br><span class="line">			System.out.println(&quot;printStackTrace():--==&quot;);</span><br><span class="line">			e.printStackTrace();</span><br><span class="line">			System.out.println(&quot;printStackTrace(System.out):--==&quot;);</span><br><span class="line">			e.printStackTrace(System.out);</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>printStackTrace（）方法所提供的信息可以使用getStackTrace（）方法获取到，这个方法返回一个由栈轨迹元素所构成的数组，其中每一个元素都表示栈中的一帧。元素0为栈顶元素，表示调用序列最后的一个方法，也就是Throwable创建和抛出的地方，数组中最后一个元素为方法调用序列中的第一个调用方法。下面程序简单演示：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line">public class WhoCalled &#123;</span><br><span class="line">	static void f()&#123;</span><br><span class="line">		try&#123;</span><br><span class="line">			throw new Exception();</span><br><span class="line">		&#125;catch(Exception e)&#123;</span><br><span class="line">			for(StackTraceElement ste : e.getStackTrace())&#123;</span><br><span class="line">				System.out.println(ste.getMethodName());</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">	static void g()&#123;</span><br><span class="line">		f();</span><br><span class="line">	&#125;</span><br><span class="line">	static void h()&#123;</span><br><span class="line">		g();</span><br><span class="line">	&#125;</span><br><span class="line">	public static void main(String[] args) &#123;</span><br><span class="line">		f();</span><br><span class="line">		System.out.println(&quot;------------&quot;);</span><br><span class="line">		g();</span><br><span class="line">		System.out.println(&quot;------------&quot;);</span><br><span class="line">		h();</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="12-7-Java标准异常"><a href="#12-7-Java标准异常" class="headerlink" title="12.7 Java标准异常"></a>12.7 Java标准异常</h2><p> Throwable这个类表示任何可以被作为异常抛出的类，Error表示编译时的系统错误，一般不需要我们关心。Exception是可以被抛出的基本类型，在Java类库、用户方法以及运行时故障都可以抛出此类异常。所以Java程序员通常需要关心此类的异常信息，同时Java异常要求可以见名知意。Java中还有一种Runtime异常，它表示程序编译错误，无法由程序员自己控制，这种异常不需要我们自己主动捕获并抛出，程序会自动抛出此类异常，如前文提到的NullPointerException。</p>
<h2 id="12-8-使用finally进行清理"><a href="#12-8-使用finally进行清理" class="headerlink" title="12.8 使用finally进行清理"></a>12.8 使用finally进行清理</h2><p>一些代码，可能希望无论是否抛出异常，这些代码都必须要执行。这通常包括内存回收之外的一些操作，因为内存回收是由垃圾回收器完成。为了达到这个效果，可以在catch块之后加上finally块。在finally块中处理这些代码。完整的异常处理如下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">try&#123;</span><br><span class="line">	//---</span><br><span class="line">&#125;catch(Exception e1)&#123;</span><br><span class="line">	//---</span><br><span class="line">&#125;catch(Exception e2)&#123;</span><br><span class="line">	//---</span><br><span class="line">&#125;finally&#123;</span><br><span class="line">	//---</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>finally字句不管异常是否抛出都能被执行：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line">public class FinallyWorks &#123;</span><br><span class="line">	static int count = 0;</span><br><span class="line">	public static void main(String[] args) &#123;</span><br><span class="line">		while(true)&#123;</span><br><span class="line">			try&#123;</span><br><span class="line">				if(count++ == 0)&#123;</span><br><span class="line">					throw new Exception();</span><br><span class="line">				&#125;</span><br><span class="line">				System.out.println(&quot;No Exception&quot;);</span><br><span class="line">				&#125;catch(Exception e)&#123;</span><br><span class="line">					System.out.println(&quot;Exception&quot;);</span><br><span class="line">				&#125;finally&#123;</span><br><span class="line">					System.out.println(&quot;In finally clause&quot;);</span><br><span class="line">					if(count == 2)&#123;</span><br><span class="line">						break;</span><br><span class="line">					&#125;</span><br><span class="line">				&#125;</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br></pre></td></tr></table></figure>

<p>不管异常是否被抛出，finally字句都执行了。这个程序告诉我们，当程序发生了异常之后不能正确的回到原来的执行顺序上，我们可以在finally块中处理一些必要做的事情。比如打开文件的操作，当文件操作发生异常的时候，我们要确保文件被正确的关闭。</p>
<h2 id="12-9-异常的限制"><a href="#12-9-异常的限制" class="headerlink" title="12.9 异常的限制"></a>12.9 异常的限制</h2><p>异常会被继承的基类和接口所限制</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br></pre></td><td class="code"><pre><span class="line">class BaseballException extends Exception&#123;</span><br><span class="line">	</span><br><span class="line">&#125;</span><br><span class="line">class Foul extends BaseballException&#123;</span><br><span class="line">	</span><br><span class="line">&#125;</span><br><span class="line">class Strike extends BaseballException&#123;</span><br><span class="line">	</span><br><span class="line">&#125;</span><br><span class="line">abstract class Inning&#123;</span><br><span class="line">	public Inning() throws BaseballException&#123;</span><br><span class="line">		</span><br><span class="line">	&#125;</span><br><span class="line">	public void event() throws BaseballException&#123;</span><br><span class="line">		</span><br><span class="line">	&#125;</span><br><span class="line">	public abstract void atBat() throws Strike,Foul;</span><br><span class="line">	public void walk()&#123;</span><br><span class="line">		</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br><span class="line">class StormException extends Exception&#123;</span><br><span class="line">	</span><br><span class="line">&#125;</span><br><span class="line">class RainedOut extends StormException&#123;</span><br><span class="line">	</span><br><span class="line">&#125;</span><br><span class="line">class PopFoul extends Foul&#123;</span><br><span class="line">	</span><br><span class="line">&#125;</span><br><span class="line">interface Storm&#123;</span><br><span class="line">	public void events() throws RainedOut;</span><br><span class="line">	public void rainHard() throws RainedOut;</span><br><span class="line">&#125;</span><br><span class="line">public class StormyInning extends Inning implements Storm&#123;</span><br><span class="line"> </span><br><span class="line">	public StormyInning() throws BaseballException &#123;</span><br><span class="line">		super();</span><br><span class="line">		// TODO Auto-generated constructor stub</span><br><span class="line">	&#125;</span><br><span class="line"> </span><br><span class="line">	@Override</span><br><span class="line">	public void rainHard() throws RainedOut &#123;</span><br><span class="line">		// TODO Auto-generated method stub</span><br><span class="line">		</span><br><span class="line">	&#125;</span><br><span class="line"> </span><br><span class="line">	@Override</span><br><span class="line">	public void atBat() throws Strike, Foul &#123;</span><br><span class="line">		// TODO Auto-generated method stub</span><br><span class="line">		</span><br><span class="line">	&#125;</span><br><span class="line"> </span><br><span class="line">	@Override</span><br><span class="line">	public void events() throws RainedOut &#123;</span><br><span class="line">		// TODO Auto-generated method stub</span><br><span class="line">		</span><br><span class="line">	&#125;</span><br><span class="line">	//抽象类中的该方法没有抛出任何异常 所以覆盖重写的时候 也不能抛出异常</span><br><span class="line">//	public void walk() throws RainedOut&#123;</span><br><span class="line">//		</span><br><span class="line">//	&#125;</span><br><span class="line">	//抽象类中的该方法抛出了异常 重写的时候可以选择不抛出异常</span><br><span class="line">//	public void event()&#123;</span><br><span class="line">//		</span><br><span class="line">//	&#125;</span><br><span class="line">	//抽象类中的该方法抛出了BaseballException 所以可以抛出其异常的子异常</span><br><span class="line">	public void event() throws Foul&#123;</span><br><span class="line">		</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>当继承或者实现一个类的时候，这个子类只能抛出基类中异常列表中的异常，或者其子异常，或者不抛出异常，但是不能抛出其它异常，或者抛出异常的基类异常。</p>
<h2 id="12-10-构造器"><a href="#12-10-构造器" class="headerlink" title="12.10 构造器"></a>12.10 构造器</h2><p>“如果异常发生了，所有东西能被正确清理吗？”大多数情况都是非常安全的，可以使用finally进行清理。但是当使用构造函数的时候，就有些问题了。比如使用构造函数构造文件操作，因为finally语句不管构造成功或者失败都会执行。假如构造失败了，如果文件没有被打开，那么这时候如果执行finally关闭文件操作就是不正确的。还有，如果文件构造成功了，因为文件需要在后边使用，所以在finally中关闭文件显然是不合理的。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line">public class InputFile &#123;</span><br><span class="line">	private BufferedReader in;</span><br><span class="line">	public InputFile(String name) throws Exception&#123;</span><br><span class="line">		try&#123;</span><br><span class="line">			in = new BufferedReader(new FileReader(name));</span><br><span class="line">		&#125;catch(FileNotFoundException e1)&#123;</span><br><span class="line">			//没有找到文件也就是文件没有打开 所以不需要清理</span><br><span class="line">			System.out.println(&quot;The file is not found&quot;);</span><br><span class="line">			throw e1;</span><br><span class="line">		&#125;catch(Exception e2)&#123;</span><br><span class="line">			//所有其它的异常都发生在文件打开之后 因此需要进行清理工作</span><br><span class="line">			try&#123;</span><br><span class="line">				in.close();</span><br><span class="line">			&#125;catch(IOException e3)&#123;</span><br><span class="line">				//---</span><br><span class="line">			&#125;</span><br><span class="line">			throw e2;</span><br><span class="line">		&#125;finally&#123;</span><br><span class="line">			//此处由于构造成功也会执行 所以不能进行文件关闭操作</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p> 对于这种需要在构造器中创建的对象，合理的做法是使用嵌套try-catch</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line">public class CleanUp &#123;</span><br><span class="line">	public static void main(String[] args) &#123;</span><br><span class="line">		try&#123;</span><br><span class="line">			InputFile in = new InputFile(&quot;CleanUp.java&quot;);</span><br><span class="line">			try&#123;</span><br><span class="line">				//</span><br><span class="line">			&#125;catch(Exception e1)&#123;</span><br><span class="line">				//此处为文件操作异常</span><br><span class="line">			&#125;finally&#123;</span><br><span class="line">				//-- 此处清理操作关闭文件</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;catch(Exception e2)&#123;</span><br><span class="line">			//--此处捕获构造异常</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="12-11-异常匹配"><a href="#12-11-异常匹配" class="headerlink" title="12.11 异常匹配"></a>12.11 异常匹配</h2><p>在抛出异常之后，异常处理系统会按照代码的编写顺序找到最近的异常处理程序并执行，此时便任务异常已经得到了处理，就不会继续进行下去。查找的时候并不要求抛出的异常同处理程序所声明的异常完全匹配，子类的对象也可以匹配到其基类的处理程序。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line">class Annyoance extends Exception&#123;</span><br><span class="line">	</span><br><span class="line">&#125;</span><br><span class="line">class Sneeze extends Annyoance&#123;</span><br><span class="line">	</span><br><span class="line">&#125;</span><br><span class="line">public class Human &#123;</span><br><span class="line">	public static void main(String[] args) &#123;</span><br><span class="line">		try&#123;</span><br><span class="line">			throw new Sneeze();</span><br><span class="line">		&#125;catch(Sneeze s)&#123;</span><br><span class="line">			System.out.println(&quot;Catch Sneeze&quot;);</span><br><span class="line">		&#125;catch(Annyoance a)&#123;</span><br><span class="line">			System.out.println(&quot;Catch Annyoance1&quot;);</span><br><span class="line">		&#125;</span><br><span class="line">		try&#123;</span><br><span class="line">			throw new Sneeze();</span><br><span class="line">		&#125;catch(Annyoance a)&#123;</span><br><span class="line">			System.out.println(&quot;Catch Annyoance2&quot;);</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p> 编译器发现Annyoance是Sneeze的基类，所以编译的过程会提示警告。</p>
<h2 id="12-12-其他可选方式"><a href="#12-12-其他可选方式" class="headerlink" title="12.12 其他可选方式"></a>12.12 其他可选方式</h2><ul>
<li>历史 在java中 对于范型用于异常说明的方式存在着一些限制。</li>
<li>观点 好的程序设计语言能帮助写出好程序，但是避免不了程序员用它写出坏程序</li>
<li>把异常传递给控制台</li>
<li>被检查的异常转换成不检查的异常 RuntimeException可以抛出异常，但是还是要用 try 捕获你想你肯定想得到的异常。</li>
</ul>
<h2 id="12-13-异常使用指南"><a href="#12-13-异常使用指南" class="headerlink" title="12.13 异常使用指南"></a>12.13 异常使用指南</h2><ol>
<li>知道如何处理情况下捕获</li>
<li>解决问题重新调用产生问题的方法</li>
<li>进行修补，绕过异常发生的地方继续执行。</li>
<li>用别的数据进行计算，以代替方法预计会返回的值。</li>
<li>把当前运行环境的事情做完，相同的异常抛出到更高层。</li>
<li>把当前运行环境的事情做完，不相同的异常抛出到更高层。</li>
<li>终止程序。</li>
<li>简化异常。</li>
<li>让类库和程序更安全。</li>
</ol>
<h2 id="12-14-总结"><a href="#12-14-总结" class="headerlink" title="12.14 总结"></a>12.14 总结</h2><p>异常是Java编程中不可或缺的一部分，它将程序正常执行的路径与错误处理分开，减少了编码判断的冗余。使用try-catch的方式进行异常处理，同时我们也可以创建自己的异常，继承其它的异常类。一些RuntimeException无需我们自己捕捉，程序会自动捕捉。注意构造器内发生异常的情况，因为构造器往往是只是简单的构造了一个对象，对象还需要使用，所以在使用finally进行清理的时候需要注意这一点。因为finally域的代码块不管异常是否发生都会执行。处理异常的时候可以使用基类Throwable提供的方法，比如使用printStackTrace打印栈的调用顺序。</p>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2019/08/07/Thinking-in-Java-第十一章/" rel="next" title="Thinking in Java 第十一章">
                <i class="fa fa-chevron-left"></i> Thinking in Java 第十一章
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2019/08/07/kafka-个人理解以及常用应用场景-kafka-zookeeper-无坑搭建/" rel="prev" title="kafka 个人理解以及常用应用场景 & kafka zookeeper 无坑搭建">
                kafka 个人理解以及常用应用场景 & kafka zookeeper 无坑搭建 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            Table of Contents
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            Overview
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="/images/avatar.jpg" alt="190coder">
            
              <p class="site-author-name" itemprop="name">190coder</p>
              <p class="site-description motion-element" itemprop="description">坚信持续学习就一定能超过大多数人</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">53</span>
                  <span class="site-state-item-name">posts</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">13</span>
                  <span class="site-state-item-name">categories</span>
                </a>
              </div>
            

            

          </nav>

          

          

          
          

          
          

          <div style>
  <canvas id="canvas" style="width:60%;">当前浏览器不支持canvas，请更换浏览器后再试</canvas>
</div>
<script>
(function(){

   var digit=
    [
        [
            [0,0,1,1,1,0,0],
            [0,1,1,0,1,1,0],
            [1,1,0,0,0,1,1],
            [1,1,0,0,0,1,1],
            [1,1,0,0,0,1,1],
            [1,1,0,0,0,1,1],
            [1,1,0,0,0,1,1],
            [1,1,0,0,0,1,1],
            [0,1,1,0,1,1,0],
            [0,0,1,1,1,0,0]
        ],//0
        [
            [0,0,0,1,1,0,0],
            [0,1,1,1,1,0,0],
            [0,0,0,1,1,0,0],
            [0,0,0,1,1,0,0],
            [0,0,0,1,1,0,0],
            [0,0,0,1,1,0,0],
            [0,0,0,1,1,0,0],
            [0,0,0,1,1,0,0],
            [0,0,0,1,1,0,0],
            [1,1,1,1,1,1,1]
        ],//1
        [
            [0,1,1,1,1,1,0],
            [1,1,0,0,0,1,1],
            [0,0,0,0,0,1,1],
            [0,0,0,0,1,1,0],
            [0,0,0,1,1,0,0],
            [0,0,1,1,0,0,0],
            [0,1,1,0,0,0,0],
            [1,1,0,0,0,0,0],
            [1,1,0,0,0,1,1],
            [1,1,1,1,1,1,1]
        ],//2
        [
            [1,1,1,1,1,1,1],
            [0,0,0,0,0,1,1],
            [0,0,0,0,1,1,0],
            [0,0,0,1,1,0,0],
            [0,0,1,1,1,0,0],
            [0,0,0,0,1,1,0],
            [0,0,0,0,0,1,1],
            [0,0,0,0,0,1,1],
            [1,1,0,0,0,1,1],
            [0,1,1,1,1,1,0]
        ],//3
        [
            [0,0,0,0,1,1,0],
            [0,0,0,1,1,1,0],
            [0,0,1,1,1,1,0],
            [0,1,1,0,1,1,0],
            [1,1,0,0,1,1,0],
            [1,1,1,1,1,1,1],
            [0,0,0,0,1,1,0],
            [0,0,0,0,1,1,0],
            [0,0,0,0,1,1,0],
            [0,0,0,1,1,1,1]
        ],//4
        [
            [1,1,1,1,1,1,1],
            [1,1,0,0,0,0,0],
            [1,1,0,0,0,0,0],
            [1,1,1,1,1,1,0],
            [0,0,0,0,0,1,1],
            [0,0,0,0,0,1,1],
            [0,0,0,0,0,1,1],
            [0,0,0,0,0,1,1],
            [1,1,0,0,0,1,1],
            [0,1,1,1,1,1,0]
        ],//5
        [
            [0,0,0,0,1,1,0],
            [0,0,1,1,0,0,0],
            [0,1,1,0,0,0,0],
            [1,1,0,0,0,0,0],
            [1,1,0,1,1,1,0],
            [1,1,0,0,0,1,1],
            [1,1,0,0,0,1,1],
            [1,1,0,0,0,1,1],
            [1,1,0,0,0,1,1],
            [0,1,1,1,1,1,0]
        ],//6
        [
            [1,1,1,1,1,1,1],
            [1,1,0,0,0,1,1],
            [0,0,0,0,1,1,0],
            [0,0,0,0,1,1,0],
            [0,0,0,1,1,0,0],
            [0,0,0,1,1,0,0],
            [0,0,1,1,0,0,0],
            [0,0,1,1,0,0,0],
            [0,0,1,1,0,0,0],
            [0,0,1,1,0,0,0]
        ],//7
        [
            [0,1,1,1,1,1,0],
            [1,1,0,0,0,1,1],
            [1,1,0,0,0,1,1],
            [1,1,0,0,0,1,1],
            [0,1,1,1,1,1,0],
            [1,1,0,0,0,1,1],
            [1,1,0,0,0,1,1],
            [1,1,0,0,0,1,1],
            [1,1,0,0,0,1,1],
            [0,1,1,1,1,1,0]
        ],//8
        [
            [0,1,1,1,1,1,0],
            [1,1,0,0,0,1,1],
            [1,1,0,0,0,1,1],
            [1,1,0,0,0,1,1],
            [0,1,1,1,0,1,1],
            [0,0,0,0,0,1,1],
            [0,0,0,0,0,1,1],
            [0,0,0,0,1,1,0],
            [0,0,0,1,1,0,0],
            [0,1,1,0,0,0,0]
        ],//9
        [
            [0,0,0,0,0,0,0],
            [0,0,1,1,1,0,0],
            [0,0,1,1,1,0,0],
            [0,0,1,1,1,0,0],
            [0,0,0,0,0,0,0],
            [0,0,0,0,0,0,0],
            [0,0,1,1,1,0,0],
            [0,0,1,1,1,0,0],
            [0,0,1,1,1,0,0],
            [0,0,0,0,0,0,0]
        ]//:
    ];

var canvas = document.getElementById('canvas');

if(canvas.getContext){
    var cxt = canvas.getContext('2d');
    //声明canvas的宽高
    var H = 100,W = 700;
    canvas.height = H;
    canvas.width = W;
    cxt.fillStyle = '#f00';
    cxt.fillRect(10,10,50,50);

    //存储时间数据
    var data = [];
    //存储运动的小球
    var balls = [];
    //设置粒子半径
    var R = canvas.height/20-1;
    (function(){
        var temp = /(\d)(\d):(\d)(\d):(\d)(\d)/.exec(new Date());
        //存储时间数字，由十位小时、个位小时、冒号、十位分钟、个位分钟、冒号、十位秒钟、个位秒钟这7个数字组成
        data.push(temp[1],temp[2],10,temp[3],temp[4],10,temp[5],temp[6]);
    })();

    /*生成点阵数字*/
    function renderDigit(index,num){
        for(var i = 0; i < digit[num].length; i++){
            for(var j = 0; j < digit[num][i].length; j++){
                if(digit[num][i][j] == 1){
                    cxt.beginPath();
                    cxt.arc(14*(R+2)*index + j*2*(R+1)+(R+1),i*2*(R+1)+(R+1),R,0,2*Math.PI);
                    cxt.closePath();
                    cxt.fill();
                }
            }
        }
    }

    /*更新时钟*/
    function updateDigitTime(){
        var changeNumArray = [];
        var temp = /(\d)(\d):(\d)(\d):(\d)(\d)/.exec(new Date());
        var NewData = [];
        NewData.push(temp[1],temp[2],10,temp[3],temp[4],10,temp[5],temp[6]);
        for(var i = data.length-1; i >=0 ; i--){
            //时间发生变化
            if(NewData[i] !== data[i]){
                //将变化的数字值和在data数组中的索引存储在changeNumArray数组中
                changeNumArray.push(i+'_'+(Number(data[i])+1)%10);
            }
        }
        //增加小球
        for(var i = 0; i< changeNumArray.length; i++){
            addBalls.apply(this,changeNumArray[i].split('_'));
        }
        data = NewData.concat();
    }

    /*更新小球状态*/
    function updateBalls(){
        for(var i = 0; i < balls.length; i++){
            balls[i].stepY += balls[i].disY;
            balls[i].x += balls[i].stepX;
            balls[i].y += balls[i].stepY;
            if(balls[i].x > W + R || balls[i].y > H + R){
                balls.splice(i,1);
                i--;
            }
        }
    }

    /*增加要运动的小球*/
    function addBalls(index,num){
        var numArray = [1,2,3];
        var colorArray =  ["#3BE","#09C","#A6C","#93C","#9C0","#690","#FB3","#F80","#F44","#C00"];
        for(var i = 0; i < digit[num].length; i++){
            for(var j = 0; j < digit[num][i].length; j++){
                if(digit[num][i][j] == 1){
                    var ball = {
                        x:14*(R+2)*index + j*2*(R+1)+(R+1),
                        y:i*2*(R+1)+(R+1),
                        stepX:Math.floor(Math.random() * 4 -2),
                        stepY:-2*numArray[Math.floor(Math.random()*numArray.length)],
                        color:colorArray[Math.floor(Math.random()*colorArray.length)],
                        disY:1
                    };
                    balls.push(ball);
                }
            }
        }
    }

    /*渲染*/
    function render(){
        //重置画布宽度，达到清空画布的效果
        canvas.height = 100;
        //渲染时钟
        for(var i = 0; i < data.length; i++){
            renderDigit(i,data[i]);
        }
        //渲染小球
        for(var i = 0; i < balls.length; i++){
            cxt.beginPath();
            cxt.arc(balls[i].x,balls[i].y,R,0,2*Math.PI);
            cxt.fillStyle = balls[i].color;
            cxt.closePath();
            cxt.fill();
        }
    }

    clearInterval(oTimer);
    var oTimer = setInterval(function(){
        //更新时钟
        updateDigitTime();
        //更新小球状态
        updateBalls();
        //渲染
        render();
    },50);
}

})();
</script>



        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#第十三章-通过异常处理错误"><span class="nav-number">1.</span> <span class="nav-text">第十三章 通过异常处理错误</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#13-1-概念"><span class="nav-number">1.1.</span> <span class="nav-text">13.1 概念</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#13-2-基本异常"><span class="nav-number">1.2.</span> <span class="nav-text">13.2 基本异常</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#13-3-捕获异常"><span class="nav-number">1.3.</span> <span class="nav-text">13.3 捕获异常</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#13-4-创建自定义异常"><span class="nav-number">1.4.</span> <span class="nav-text">13.4 创建自定义异常</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#12-5-异常说明"><span class="nav-number">1.5.</span> <span class="nav-text">12.5 异常说明</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#12-6-捕获所有异常"><span class="nav-number">1.6.</span> <span class="nav-text">12.6 捕获所有异常</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#12-7-Java标准异常"><span class="nav-number">1.7.</span> <span class="nav-text">12.7 Java标准异常</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#12-8-使用finally进行清理"><span class="nav-number">1.8.</span> <span class="nav-text">12.8 使用finally进行清理</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#12-9-异常的限制"><span class="nav-number">1.9.</span> <span class="nav-text">12.9 异常的限制</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#12-10-构造器"><span class="nav-number">1.10.</span> <span class="nav-text">12.10 构造器</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#12-11-异常匹配"><span class="nav-number">1.11.</span> <span class="nav-text">12.11 异常匹配</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#12-12-其他可选方式"><span class="nav-number">1.12.</span> <span class="nav-text">12.12 其他可选方式</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#12-13-异常使用指南"><span class="nav-number">1.13.</span> <span class="nav-text">12.13 异常使用指南</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#12-14-总结"><span class="nav-number">1.14.</span> <span class="nav-text">12.14 总结</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

	
           
         
         <div style>
  <canvas id="canvas" style="width:60%;">当前浏览器不支持canvas，请更换浏览器后再试</canvas>
</div>
<script>
(function(){

   var digit=
    [
        [
            [0,0,1,1,1,0,0],
            [0,1,1,0,1,1,0],
            [1,1,0,0,0,1,1],
            [1,1,0,0,0,1,1],
            [1,1,0,0,0,1,1],
            [1,1,0,0,0,1,1],
            [1,1,0,0,0,1,1],
            [1,1,0,0,0,1,1],
            [0,1,1,0,1,1,0],
            [0,0,1,1,1,0,0]
        ],//0
        [
            [0,0,0,1,1,0,0],
            [0,1,1,1,1,0,0],
            [0,0,0,1,1,0,0],
            [0,0,0,1,1,0,0],
            [0,0,0,1,1,0,0],
            [0,0,0,1,1,0,0],
            [0,0,0,1,1,0,0],
            [0,0,0,1,1,0,0],
            [0,0,0,1,1,0,0],
            [1,1,1,1,1,1,1]
        ],//1
        [
            [0,1,1,1,1,1,0],
            [1,1,0,0,0,1,1],
            [0,0,0,0,0,1,1],
            [0,0,0,0,1,1,0],
            [0,0,0,1,1,0,0],
            [0,0,1,1,0,0,0],
            [0,1,1,0,0,0,0],
            [1,1,0,0,0,0,0],
            [1,1,0,0,0,1,1],
            [1,1,1,1,1,1,1]
        ],//2
        [
            [1,1,1,1,1,1,1],
            [0,0,0,0,0,1,1],
            [0,0,0,0,1,1,0],
            [0,0,0,1,1,0,0],
            [0,0,1,1,1,0,0],
            [0,0,0,0,1,1,0],
            [0,0,0,0,0,1,1],
            [0,0,0,0,0,1,1],
            [1,1,0,0,0,1,1],
            [0,1,1,1,1,1,0]
        ],//3
        [
            [0,0,0,0,1,1,0],
            [0,0,0,1,1,1,0],
            [0,0,1,1,1,1,0],
            [0,1,1,0,1,1,0],
            [1,1,0,0,1,1,0],
            [1,1,1,1,1,1,1],
            [0,0,0,0,1,1,0],
            [0,0,0,0,1,1,0],
            [0,0,0,0,1,1,0],
            [0,0,0,1,1,1,1]
        ],//4
        [
            [1,1,1,1,1,1,1],
            [1,1,0,0,0,0,0],
            [1,1,0,0,0,0,0],
            [1,1,1,1,1,1,0],
            [0,0,0,0,0,1,1],
            [0,0,0,0,0,1,1],
            [0,0,0,0,0,1,1],
            [0,0,0,0,0,1,1],
            [1,1,0,0,0,1,1],
            [0,1,1,1,1,1,0]
        ],//5
        [
            [0,0,0,0,1,1,0],
            [0,0,1,1,0,0,0],
            [0,1,1,0,0,0,0],
            [1,1,0,0,0,0,0],
            [1,1,0,1,1,1,0],
            [1,1,0,0,0,1,1],
            [1,1,0,0,0,1,1],
            [1,1,0,0,0,1,1],
            [1,1,0,0,0,1,1],
            [0,1,1,1,1,1,0]
        ],//6
        [
            [1,1,1,1,1,1,1],
            [1,1,0,0,0,1,1],
            [0,0,0,0,1,1,0],
            [0,0,0,0,1,1,0],
            [0,0,0,1,1,0,0],
            [0,0,0,1,1,0,0],
            [0,0,1,1,0,0,0],
            [0,0,1,1,0,0,0],
            [0,0,1,1,0,0,0],
            [0,0,1,1,0,0,0]
        ],//7
        [
            [0,1,1,1,1,1,0],
            [1,1,0,0,0,1,1],
            [1,1,0,0,0,1,1],
            [1,1,0,0,0,1,1],
            [0,1,1,1,1,1,0],
            [1,1,0,0,0,1,1],
            [1,1,0,0,0,1,1],
            [1,1,0,0,0,1,1],
            [1,1,0,0,0,1,1],
            [0,1,1,1,1,1,0]
        ],//8
        [
            [0,1,1,1,1,1,0],
            [1,1,0,0,0,1,1],
            [1,1,0,0,0,1,1],
            [1,1,0,0,0,1,1],
            [0,1,1,1,0,1,1],
            [0,0,0,0,0,1,1],
            [0,0,0,0,0,1,1],
            [0,0,0,0,1,1,0],
            [0,0,0,1,1,0,0],
            [0,1,1,0,0,0,0]
        ],//9
        [
            [0,0,0,0,0,0,0],
            [0,0,1,1,1,0,0],
            [0,0,1,1,1,0,0],
            [0,0,1,1,1,0,0],
            [0,0,0,0,0,0,0],
            [0,0,0,0,0,0,0],
            [0,0,1,1,1,0,0],
            [0,0,1,1,1,0,0],
            [0,0,1,1,1,0,0],
            [0,0,0,0,0,0,0]
        ]//:
    ];

var canvas = document.getElementById('canvas');

if(canvas.getContext){
    var cxt = canvas.getContext('2d');
    //声明canvas的宽高
    var H = 100,W = 700;
    canvas.height = H;
    canvas.width = W;
    cxt.fillStyle = '#f00';
    cxt.fillRect(10,10,50,50);

    //存储时间数据
    var data = [];
    //存储运动的小球
    var balls = [];
    //设置粒子半径
    var R = canvas.height/20-1;
    (function(){
        var temp = /(\d)(\d):(\d)(\d):(\d)(\d)/.exec(new Date());
        //存储时间数字，由十位小时、个位小时、冒号、十位分钟、个位分钟、冒号、十位秒钟、个位秒钟这7个数字组成
        data.push(temp[1],temp[2],10,temp[3],temp[4],10,temp[5],temp[6]);
    })();

    /*生成点阵数字*/
    function renderDigit(index,num){
        for(var i = 0; i < digit[num].length; i++){
            for(var j = 0; j < digit[num][i].length; j++){
                if(digit[num][i][j] == 1){
                    cxt.beginPath();
                    cxt.arc(14*(R+2)*index + j*2*(R+1)+(R+1),i*2*(R+1)+(R+1),R,0,2*Math.PI);
                    cxt.closePath();
                    cxt.fill();
                }
            }
        }
    }

    /*更新时钟*/
    function updateDigitTime(){
        var changeNumArray = [];
        var temp = /(\d)(\d):(\d)(\d):(\d)(\d)/.exec(new Date());
        var NewData = [];
        NewData.push(temp[1],temp[2],10,temp[3],temp[4],10,temp[5],temp[6]);
        for(var i = data.length-1; i >=0 ; i--){
            //时间发生变化
            if(NewData[i] !== data[i]){
                //将变化的数字值和在data数组中的索引存储在changeNumArray数组中
                changeNumArray.push(i+'_'+(Number(data[i])+1)%10);
            }
        }
        //增加小球
        for(var i = 0; i< changeNumArray.length; i++){
            addBalls.apply(this,changeNumArray[i].split('_'));
        }
        data = NewData.concat();
    }

    /*更新小球状态*/
    function updateBalls(){
        for(var i = 0; i < balls.length; i++){
            balls[i].stepY += balls[i].disY;
            balls[i].x += balls[i].stepX;
            balls[i].y += balls[i].stepY;
            if(balls[i].x > W + R || balls[i].y > H + R){
                balls.splice(i,1);
                i--;
            }
        }
    }

    /*增加要运动的小球*/
    function addBalls(index,num){
        var numArray = [1,2,3];
        var colorArray =  ["#3BE","#09C","#A6C","#93C","#9C0","#690","#FB3","#F80","#F44","#C00"];
        for(var i = 0; i < digit[num].length; i++){
            for(var j = 0; j < digit[num][i].length; j++){
                if(digit[num][i][j] == 1){
                    var ball = {
                        x:14*(R+2)*index + j*2*(R+1)+(R+1),
                        y:i*2*(R+1)+(R+1),
                        stepX:Math.floor(Math.random() * 4 -2),
                        stepY:-2*numArray[Math.floor(Math.random()*numArray.length)],
                        color:colorArray[Math.floor(Math.random()*colorArray.length)],
                        disY:1
                    };
                    balls.push(ball);
                }
            }
        }
    }

    /*渲染*/
    function render(){
        //重置画布宽度，达到清空画布的效果
        canvas.height = 100;
        //渲染时钟
        for(var i = 0; i < data.length; i++){
            renderDigit(i,data[i]);
        }
        //渲染小球
        for(var i = 0; i < balls.length; i++){
            cxt.beginPath();
            cxt.arc(balls[i].x,balls[i].y,R,0,2*Math.PI);
            cxt.fillStyle = balls[i].color;
            cxt.closePath();
            cxt.fill();
        }
    }

    clearInterval(oTimer);
    var oTimer = setInterval(function(){
        //更新时钟
        updateDigitTime();
        //更新小球状态
        updateBalls();
        //渲染
        render();
    },50);
}

})();
</script>



    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">190coder</span>

  
</div>


  <div class="powered-by">Powered by <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a></div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">Theme &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Gemini</a> v5.1.4</div>





<div>
    <script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
    <span id="busuanzi_container_site_pv">本站总访问量<span id="busuanzi_value_site_pv"></span>次</span>
    <span class="post-meta-divider">|</span>
    <span id="busuanzi_container_site_uv">本站访客数<span id="busuanzi_value_site_uv"></span>人</span>
</div>


        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  


  











  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  

  
  
    <script type="text/javascript" src="//cdn.jsdelivr.net/gh/theme-next/theme-next-canvas-nest@1/canvas-nest.min.js"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  





  

  

  

  
  

  

  

  

</body>
</html>
